package com.tianji.login.service.Impl;/**
 * @author ChenJia
 * @create 2023-05-31 21:52
 */

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.tianji.login.dto.AuthParamsDto;
import com.tianji.login.mapper.SysUserMapper;
import com.tianji.login.pojo.SysUser;
import com.tianji.login.pojo.XcUserExt;
import com.tianji.login.service.AuthService;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

/**
 *@ClassName PasswordAuthServiceImpl
 *@Description 账号密码认证
 *@Author jia
 *@Date 2023/5/31 21:52
 *@Version 1.0
 **/
@Slf4j
@Service("password_authservice")
public class PasswordAuthServiceImpl implements AuthService {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private SysUserMapper xcUserMapper;

    @Override
    public XcUserExt execute(AuthParamsDto authParamsDto) {
        //校验验证码
        String checkcode = authParamsDto.getCheckcode();//用户输入放入验证码
        String checkcodekey = authParamsDto.getCheckcodekey();//验证码的key
        if(StringUtils.isBlank(checkcodekey) || StringUtils.isBlank(checkcode)){
            throw new RuntimeException("请输入验证码");
        }
        //验证码

        //账号
        String username = authParamsDto.getUsername();
        //从数据库中取出信息
        SysUser xcUser = xcUserMapper.selectOne(new LambdaQueryWrapper<SysUser>()
                .eq(SysUser::getUsername, username));
        if(xcUser == null){
            throw new RuntimeException("用户不存在");
        }

        //检验密码
        String passwordDb = xcUser.getPassword();
        String passwordFrom = authParamsDto.getPassword();
        boolean matches = passwordEncoder.matches(passwordFrom, passwordDb);
        if(!matches){
            throw new RuntimeException("密码输入不正确");
        }

        //返回用户信息包装成jwt返回给客户端
        XcUserExt xcUserExt = new XcUserExt();
        BeanUtils.copyProperties(xcUser,xcUserExt);

        //远程调用接口验证
        return xcUserExt;
    }
}
